package org.rency.crawler.fetch.handler.impl;

import java.util.Collection;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.rency.crawler.common.exception.CrawlerException;
import org.rency.crawler.domain.queue.FetchQueue;
import org.rency.crawler.domain.state.FetchStatus;
import org.rency.crawler.fetch.handler.AbstractFetchHandler;
import org.rency.crawler.fetch.helper.FetchCarrier;
import org.rency.crawler.fetch.repository.FetchedQueueRepository;
import org.rency.crawler.integration.queue.FetchQueueClient;
import org.springframework.stereotype.Component;

/**
 * 名称:FetchSeedHandler
 * 描述:${TODO}
 *
 * @author:rency
 * @version:V1.0.0
 * @JDK 1.8
 * @since 2017/11/22 22:20
 */
@Component
public class FetchSeedHandler extends AbstractFetchHandler{

  @Resource
  private FetchQueueClient       fetchQueueClient;

  @Resource
  private FetchedQueueRepository fetchedQueueRepository;

  @Override
  protected String getHandlerName() {
    return "种子处理";
  }

  @Override
  protected void onHandler(FetchCarrier carrier) throws CrawlerException {
    carrier.getFetchState().setFsStatus(FetchStatus.SUCCESS);
    if(CollectionUtils.isNotEmpty(carrier.getFetchQueueCollection())){
      Collection<FetchQueue> list = carrier.getFetchQueueCollection()
          .parallelStream()
          .filter(queue -> !fetchedQueueRepository.exists(queue.getFetchNo()))
          .collect(Collectors.toList());
      list.forEach(queue -> fetchQueueClient.publish(queue));
    };
  }
}
